package com.bawei.home

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.fragment.app.activityViewModels
import com.bawei.aspect.annotation.CheckLogin
import com.bawei.common.mvi.BaseMviFragment
import com.bawei.home.adapter.ViewPageAdapter
import com.bawei.home.databinding.FragmentHomeBinding
import com.bawei.home.entity.SimpleTypeEntity
import com.bawei.home.viewmodel.HomeViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * 视频首页
 */
@AndroidEntryPoint
class HomeFragment : BaseMviFragment<FragmentHomeBinding>() {

    private val  mViewModel: HomeViewModel by activityViewModels()

    private val searchHints = mutableListOf("热门视频推荐", "今日头条视频", "巴以冲突最新消息", "春节放假区去哪里")
    private var tabs = mutableListOf<SimpleTypeEntity>()
    private val fragments = mutableListOf<Fragment>()

    private lateinit var pageAdapter: ViewPageAdapter


    override fun getLayoutId(): Int = R.layout.fragment_home

    override fun initViews() {
        //设置本地数据
        mDataBinding.tvbSearch.setDatas(searchHints)
        //消息按钮点击事件
        mDataBinding.ivMsg.setOnClickListener {
            openMessagePage()
        }
        //分类菜单的点击事件
        mDataBinding.ivTypeMenu.setOnClickListener {
            showToastMessage("分类菜单！！")
        }
        //Tab关联ViewPager
        mDataBinding.tabTypeLayout.setupWithViewPager(mDataBinding.vp)
        //设置Viewpager

    }

    @CheckLogin
    fun openMessagePage(){
        showToastMessage("消息正在路上！！！")
    }

    override suspend fun sendViewIntent() {
        mViewModel.channel.send(HomeViewIntent.GetSimpleType)
    }

    override suspend fun collectUIState() {
        mViewModel.uiState.collect{
            when(it){
                is HomeUiState.LoadSimpleTypeSuccess -> {
                    initFragments(it.list)
                }
                is HomeUiState.LoadSimpleTypeFail -> {
                    showToastMessage(it.msg)
                }
                else -> {}
            }
        }


    }

    private fun initFragments(list: List<SimpleTypeEntity>){
        if(list.isNotEmpty()){
            tabs.clear()
            fragments.clear()
            //推荐Tab实体
            tabs.add(SimpleTypeEntity("", 0,-1, 0, "", "推荐"))
            fragments.add(ListFragment.newInstance(-1, ""))
            //添加分类Fragment
            list.forEach { item ->
                tabs.add(item)
                fragments.add(ListFragment.newInstance(item.id, item.channelid))
            }
            //采用ViewPager的懒加载实现，且只有当前Fragment可见的才加载
            pageAdapter = ViewPageAdapter(fragments, parentFragmentManager, FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, tabs)
            mDataBinding.vp.adapter = pageAdapter
            pageAdapter.notifyDataSetChanged()
        }
    }


}